package convert;

import java.nio.ByteBuffer;

/**
 * Create Time: 2018年01月26日 13:50
 *
 * @author fin
 */
public abstract class AbstractPackageConverter implements PackageConverter {

    private static final Integer BYTE_ALLOCATE_SIZE = 8;

    protected static final Integer INT_LENGTH = 4;

    protected static final Integer LONG_LENGTH = 8;

    protected ByteBuffer buffer = ByteBuffer.allocate(BYTE_ALLOCATE_SIZE);

    protected byte[] int2bytes(int a) {
        return new byte[] {
                (byte) ((a >> 24) & 0xFF),
                (byte) ((a >> 16) & 0xFF),
                (byte) ((a >> 8) & 0xFF),
                (byte) (a & 0xFF)
        };
    }

    protected byte[] long2bytes(long x) {
        buffer.putLong(0, x);
        return buffer.array();
    }

    //byte 数组与 int 的相互转换
    protected int bytes2int(byte[] b) {
        return   b[3] & 0xFF |
                (b[2] & 0xFF) << 8 |
                (b[1] & 0xFF) << 16 |
                (b[0] & 0xFF) << 24;
    }

    protected long bytes2long(byte[] bytes) {
        buffer.put(bytes, 0, bytes.length);
        buffer.flip();//need flip
        return buffer.getLong();
    }
}
